package org.xnat.xnatfs.util;

public class PathUtils {

  /**
   * Get the root of the path, i.e. everything up to the last "."
   */
  static public String root ( String path ) {
    int idx = path.lastIndexOf ( "." );
    if ( idx <= 0 ) {
      return path;
    }
    return path.substring ( 0, idx );
  }

  /**
   * Get the tail of the path, i.e. everything past the last "/"
   */
  static public String tail ( String path ) {
    if ( path.endsWith ( "/" ) ) {
      return tail ( path.substring ( 0, path.length () - 1 ) );
    }
    int idx = path.lastIndexOf ( "/" );
    if ( idx < 0 ) {
      return path;
    }
    return path.substring ( idx + 1 );
  }

  /**
   * Get the extension of the path, i.e. everything past the last "."
   */
  static public String extension ( String path ) {
    int idx = path.lastIndexOf ( "." );
    if ( idx == -1 ) {
      return "";
    }
    return path.substring ( path.lastIndexOf ( "." ) );
  }

  static public String dirname ( String path ) {
    if ( path.endsWith ( "/" ) ) {
      return dirname ( path.substring ( 0, path.length () - 1 ) );
    }
    int idx = path.lastIndexOf ( "/" );
    if ( idx < 0 ) {
      return path;
    }
    if ( idx == 0 ) {
      return "/";
    }
    return path.substring ( 0, idx );
  }

}
